<?php

namespace app\common\reptile;

use app\admin\model\Company;
use DOMDocument;
use DOMXPath;
use GuzzleHttp\Client;
use think\Exception;

/**
 * create by PhpStorm 2025/8/3 18:25
 * szyc.com app\common\reptile@cnnc_zhiye_com
 * 行止之行 <xingzhi8711@gmail.com>
 * 中国核工业集团-中核人才招聘网 数据抓取任务
 */
class cnnc_zhiye_com
{
    private $method = "cnnc_zhiye_com";
    public  function initCompany()
    {
        $companyJson = file_get_contents(APP_PATH."/extra/company.json");
        $company = json_decode($companyJson,true);
        foreach ($company as $k=>$v){
            $data['name']=$k;
            $data['link']="https://cnnc.zhiye.com".$v['link'];
            $res=Company::get($data);
            if(!$res){
                $res=Company::create($data);
            }
            if(isset($v['subsidiaries']) && $v['subsidiaries']){
                $this->addChild($v['subsidiaries'],$res);
            }
        }
    }
    public function addChild($data,$parent)
    {
        foreach ($data as $k=>$v) {
            $cdata['pid']=$parent->id;
            $cdata['pname']=$parent->name;
            $cdata['name']=$v['name'];
            $cdata['link']="https://cnnc.zhiye.com".$v['link'];
            $res=Company::get($cdata);
            if(!$res){
                $res=Company::create($cdata);
            }
            if(isset($v['subsidiaries']) && $v['subsidiaries']){
                $this->addChild($v['subsidiaries'],$res);
            }
        }
    }
    public function init()
    {
        $websiteList=config('websitepath.'.$this->method);
        try {
//            setLog(__METHOD__,$websiteList);
            foreach ($websiteList['path_list'] as $website){
                for ($i=1;$i<=$website['total_page'];$i++){
                    $client = new Client([
                        'base_uri' => $websiteList['web_url'], // 基础 URL
                        'timeout'  => 5.0, // 超时时间（秒）
                        'headers'  => [
                            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                        ],
                    ]);
                    $path=$website['value']."/?PageIndex=".$i;
                    $response = $client->get($path); // 获取首页
                    $html = $response->getBody()->getContents();
                    $datas=$this->cnnc_zhiye_com_metch($html);
                    setLog(__METHOD__,$datas);
                    setLog(__METHOD__,$i);
                    if(!$datas){
                        setLog(__METHOD__,"数据错误");
                        continue;
                    }
                    foreach ($datas as $data){
                        if($data['发布时间']>$websiteList['lose_time']){
                            $data['来源']=$websiteList['web_url'].$path;
                            $data['来源官网']=$websiteList['web_url'];
                            $data['网站名称']=$websiteList['web_title'];
                            $data['公司名称']=$websiteList['companey'];
                            $this->insert($data);
                        }else{
                            setLog(__METHOD__,"不符合入库条件");
                            setLog(__METHOD__,$data['发布时间']);
                            setLog(__METHOD__,$websiteList['lose_time']);
                        }
                    }

                }
            }
            return true;
        } catch (Exception $e) {
            setLog(__METHOD__,$e->getMessage());
            return false;
        }
    }
    private function cnnc_zhiye_com_metch($html)
    {
        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        if (!$dom->loadHTML($html)) {
            // 处理加载错误
            foreach(libxml_get_errors() as $error) {
                setLog(__METHOD__,$error);
            }
            libxml_clear_errors();
            return false;
        }

        // 清除错误
        libxml_clear_errors();
        $xpath = new DOMXPath($dom);
        $positions = [];

        // 选择所有的 .item 元素
        $itemNodes = $xpath->query('//div[@class="item"]');

        foreach ($itemNodes as $item) {
            $position = [];

            // 提取岗位名称
            $titleNode = $xpath->query('.//div[@class="t"]', $item)->item(0);
            if ($titleNode && $titleNode->nodeType === XML_ELEMENT_NODE) {
                $position['岗位名称'] = trim($titleNode->nodeValue);
            }

            // 提取招聘单位
            $companyNodes = $xpath->query('.//span[contains(text(), "招聘单位：")]', $item);
            if ($companyNodes->length > 0) {
                $companyText = trim($companyNodes->item(0)->nodeValue);
                // 使用正则表达式提取括号内的内容
                if (preg_match('/招聘单位：(.+)/', $companyText, $matches)) {
                    $position['招聘单位'] = trim($matches[1]);
                }
            }

            // 提取职位类别
            $categoryNodes = $xpath->query('.//span[contains(text(), "职位类别：")]', $item);
            if ($categoryNodes->length > 0) {
                $categoryText = trim($categoryNodes->item(0)->nodeValue);
                if (preg_match('/职位类别：(.+)/', $categoryText, $matches)) {
                    $position['职位类别'] = trim($matches[1]);
                }
            }

            // 提取工作地点
            $locationNodes = $xpath->query('.//span[contains(text(), "工作地点：")]', $item);
            if ($locationNodes->length > 0) {
                $locationText = trim($locationNodes->item(0)->nodeValue);
                if (preg_match('/工作地点：(.+)/', $locationText, $matches)) {
                    $position['工作地点'] = trim($matches[1]);
                }
            }

            // 提取发布时间
            $dateNodes = $xpath->query('.//span[contains(text(), "发布时间：")]', $item);
            if ($dateNodes->length > 0) {
                $dateText = trim($dateNodes->item(0)->nodeValue);
                if (preg_match('/发布时间：(.+)/', $dateText, $matches)) {
                    $position['发布时间'] = trim($matches[1]);
                }
            }
            // 提取岗位职责
            $responsibilityNodes = $xpath->query('.//div[@class="block"][h5[text()="岗位职责："]]/p', $item);
            if ($responsibilityNodes->length > 0) {
                $clone = $responsibilityNodes->item(0)->cloneNode(true);
                $position['岗位职责'] = $dom->saveHTML($clone);
            }

            // 提取任职要求
            $requirementNodes = $xpath->query('.//div[@class="block"][h5[text()="任职要求："]]/p', $item);
            if ($requirementNodes->length > 0) {
                $clone = $requirementNodes->item(0)->cloneNode(true);
                $position['任职要求'] = $dom->saveHTML($clone);
            }

            // 如果提取到有效信息，则添加到数组中
            if (!empty($position)) {
                $positions[] = $position;
            }
        }
        return $positions;

    }

    /*录入数据*/
    private function insert($data)
    {
//        return true;
        setLog(__METHOD__,$data);
        $fieldMap=config('fieldmap');
        $insertData = [];
        foreach ($data as $k=>$v){
            if(!isset($fieldMap[$k])) continue;
            $field=$fieldMap[$k];
            $insertData[$field]=$v;
        }
        $idStr=(isset($insertData['companey_name'])?$insertData['companey_name']:"")
            .(isset($insertData['child_companey_name'])?$insertData['child_companey_name']:"")
            .(isset($insertData['web_url'])?$insertData['web_url']:"")
            .(isset($insertData['work_localtion'])?$insertData['work_localtion']:"")
            .(isset($insertData['category_name'])?$insertData['category_name']:"");
        if(!$idStr){
            return false;
        }
        $uniqueId=md5($idStr);
        $insertData['uniquid']=$uniqueId;
        $companyName=isset($insertData['child_companey_name'])?$insertData['child_companey_name']:"";
        $company=Company::get(['name'=>$companyName]);
        if(!$company){
            $base=Company::get(1);
            $company=Company::create(['name'=>$companyName,'pname'=>$base->name,'pid'=>$base->id,'link'=>$base->link]);
        }
        $insertData['company_id']=$company?$company['id']:0;
        $insertData['source']="中核集团";
        $list=\app\admin\model\Job::get(['uniquid'=>$uniqueId]);
        if(!$list) {
            \app\admin\model\Job::create($insertData);
        }elseif($list->company_id<=0){
            $list->save($insertData);
        }
        return true;
    }
}